package com.deuwise.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.deuwise.common.base.AccountValidatorUtil;
import com.deuwise.common.utils.*;
import com.deuwise.common.utils.poi.ExcelData;
import com.deuwise.common.utils.poi.ExcelUtil;
import com.deuwise.common.utils.poi.ExportExcelUtils;
import com.deuwise.common.utils.poi.ImportError;
import com.deuwise.common.validator.AbstractAssert;
import com.deuwise.common.validator.ValidatorUtils;
import com.deuwise.common.validator.group.AddGroup;
import com.deuwise.common.validator.group.UpdateGroup;
import com.deuwise.system.entity.DeptDO;
import com.deuwise.system.entity.PassWordLogDo;
import com.deuwise.system.entity.SysRole;
import com.deuwise.system.entity.SysUser;
import com.deuwise.system.entity.from.PassConfigForm;
import com.deuwise.system.entity.from.PasswordForm;
import com.deuwise.system.mapper.DeptDoMapper;
import com.deuwise.system.service.*;

import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.websocket.server.PathParam;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author deuwise
 * @date 2018-11-06 14:15:04
 */
@Api(tags = "系统用户模块", description = "系统用户模块")
@RequestMapping("api/SysUser")
@RestController()
public class SysUserController extends AbstractController {
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private PassWordLogDoService passWordLogDoService;

    @ApiOperation("检测密码是否过期")
    @GetMapping("/checkPassWordLater")
    @RequiresAuthentication
    public R  checkPassWordLater(){
        PassConfigForm configForm=configDoService.getPassWordConfig();
        if(configForm.isOverDue()){
            if(StringUtils.isNotBlank(configForm.getOverDueDay())){
                //有效期
                Integer days=Integer.parseInt(configForm.getOverDueDay());
                //设置过期时间
                Date setPassOverDay=configForm.getUpdateTime();
                //最新更新密码时间
                Date newUpdateTime=passWordLogDoService.getMaxUpdateTime(getUserId());
                Calendar aCalendar = Calendar.getInstance();
                aCalendar.setTime(new Date());
                int day1 = aCalendar.get(Calendar.DAY_OF_YEAR);
                if(newUpdateTime!=null&&newUpdateTime.getTime()>setPassOverDay.getTime()){
                    aCalendar.setTime(newUpdateTime);
                    int day2 = aCalendar.get(Calendar.DAY_OF_YEAR);
                    int day=day1-day2;
                    //超过相差日期
                    if(day>days){
                        return  R.ok(true);
                    }
                }else{
                    aCalendar.setTime(setPassOverDay);
                    int day2 = aCalendar.get(Calendar.DAY_OF_YEAR);
                    int day=day1-day2;
                    //超过相差日期
                    if(day>days){
                        return  R.ok(true);
                    }
                }

            }
        }
        return  R.ok(false);
    }

    @ApiOperation(value = "新增用户信息")
    @PostMapping()
    public R insertSysUser(@RequestBody @Validated SysUser sysUser) {
        ValidatorUtils.validateEntity(sysUser, AddGroup.class);
        boolean isSuccess = false;
        if (null == sysUser) {
            return R.error(500, "新增数据失败，请稍后再试!");
        }
        int count = sysUserService.queryByUserName(sysUser.getUsername(), null);
        if (count > 0) {
            return R.error(500, "登录名称已存在");
        }
        if (null == sysUser) {
            return R.error(500, "新增数据失败，请稍后再试!");
        }

        StringBuffer strBuf = new StringBuffer("密码必须由");
        boolean pass = true;
        pass = AccountValidatorUtil.validatorPass(sysUser.getPassword(), strBuf);
        if (!pass) {
            return R.error(strBuf.substring(0, strBuf.length() - 1) + "组成");
        }
        isSuccess = sysUserService.save(sysUser);
        SysRole sysRole = new SysRole();
        sysRole.setId(sysUser.getId());
        sysRole.setCreateTime(new Date());
        sysRole.setInvented(1);
        sysRole.setRoleName(sysUser.getName() + "虚拟角色授权使用");
        sysRole.setCreateAt(getUserId());
        sysRole.setUpdateTime(new Date());
        sysRoleService.insert(sysRole);
        sysUserRoleService.saveOrUpdate(sysUser.getId(), sysUser.getRoleIdList());
        if (isSuccess) {
            return R.ok();
        } else {
            return R.error(500, "新增数据失败，请稍后再试!");
        }
    }

    @ApiOperation(value = "批量删除记录")
    @RequiresPermissions("sys:user:delete")
    @RequestMapping(value = "/deleteSelect", method = RequestMethod.POST)
    public R deleteSelect(@ApiParam(value = "ids集合", name = "ids", required = true) @RequestParam String[] ids) {
        try {

            if (Arrays.asList(ids).stream().filter(f -> f.equals("1")).count() > 0) {
                return R.error("系统管理员不能删除");
            }
            if (Arrays.asList(ids).stream().filter(f -> f.equals(getUserId())).count() > 0) {
                return R.error("当前用户不能删除");
            }

            if (ids != null && ids.length > 0) {

                sysUserService.deleteBatchIds(Arrays.asList(ids));
                sysRoleService.deleteBatchIds(Arrays.asList(ids));
            }
        } catch (Exception ex) {
            return R.error("删除失败");
        }
        return R.ok();
    }


    @Autowired
    private DeptDOService deptDOService;


    /**
     * 所有用户列表
     */
    @ApiOperation("所有用户信息")
    @GetMapping("/list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "currentPage", value = "开始页数", defaultValue = "1", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页多少条", defaultValue = "15", dataType = "int", paramType = "query")})
    @RequiresPermissions("sys:user:list")
    public Result<Page<SysUser>> list(SysUser sysUser) {
        //只有超级管理员，才能查看所有管理员列表
        Wrapper<SysUser> wrapper = new EntityWrapper<SysUser>().orderBy("id", false);

        if (sysUser != null) {
            if (StringUtils.isNotBlank(sysUser.getName())) {
                wrapper.like("name", sysUser.getName());
            }
            if (StringUtils.isNotBlank(sysUser.getDeptId())) {
                //DeptDO deptDO=new DeptDO();
               // deptDO.setParentId(sysUser.getDeptId());
               List<DeptDO> list= deptDOService.selectList(null);
                List<DeptDO> deptDOList=deptDOService.getAllDept(list,sysUser.getDeptId());
                if(deptDOList!=null&&deptDOList.size()>0) {
                    List<String> stringList = deptDOList.stream().map(DeptDO::getId).collect(Collectors.toList());
                    stringList.add(sysUser.getDeptId());
                    wrapper.in("dept_id", stringList);
                }else{
                    wrapper.in("dept_id", sysUser.getDeptId());
                }
            }
            if (sysUser.getStatus() != null && sysUser.getStatus() != -1) {
                wrapper.eq("status", sysUser.getStatus());
            }
        }
        wrapper.ne("id", "1");
       // wrapper.orderBy("id", false);
        Page<SysUser> page = sysUserService.selectPage(getPage(SysUser.class), wrapper);
        if (page != null && page.getRecords() != null && page.getRecords().size() > 0) {
            for (SysUser sysUser1 : page.getRecords()) {
                sysUser1.setPassword(Base64Utils.decodeBase64(sysUser1.getPassword()));
                List<String> roleIdList = sysUserRoleService.queryRoleIdList(sysUser1.getId());
                sysUser1.setRoleIdList(roleIdList);
                if(StringUtils.isNotBlank(sysUser1.getDeptId())){
                   DeptDO deptD= deptDOService.selectById(sysUser1.getDeptId());
                   if(deptD!=null) {
                       sysUser1.setDeptName(deptD.getName());
                   }
                }
            }
        }
        return Result.ok(page);
    }

    /**
     * 获取登录的用户信息
     */
    @ApiOperation("获取登录的用户信息")
    @GetMapping("/info")
    @RequiresAuthentication
    public R info() {
        return R.ok().put("user", getUser());
    }

    /**
     * 根据登录名称获取用户信息
     */
    @ApiOperation("根据登录名称获取用户信息")
    @GetMapping("/queryByUserName")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userName", value = "登录名称", dataType = "String", paramType = "query", required = true)})
    public R queryByUserName(String userName) {
        SysUser sysUser = sysUserService.queryByUserName(userName);
        return R.ok(sysUser);
    }

    @Autowired
    private ConfigDoService configDoService;



    /**
     * 修改登录用户密码
     */
    @ApiOperation("修改密码")
    @PostMapping("/password")
    @RequiresAuthentication
    public R password(@RequestBody PasswordForm form) {
        AbstractAssert.isBlank(form.getNewPassword(), "新密码不为能空");

        //String alertInfo = "密码必须由";
        StringBuffer strBuf = new StringBuffer("密码必须由");
        boolean pass = true;
        pass = AccountValidatorUtil.validatorPass(form.getNewPassword(), strBuf);
        if (!pass) {
            return R.error(strBuf.substring(0, strBuf.length() - 1) + "组成");
        }
        String password = Base64Utils.base64Encrypt(form.getPassword());
        //base64加密
        String newPassword = Base64Utils.base64Encrypt(form.getNewPassword());

        //更新密码
        boolean flag = sysUserService.updatePassword(getUserId(), password, newPassword);
        if (!flag) {
            return R.error("原密码不正确");
        }
        try {
            PassWordLogDo passWordLogDo = new PassWordLogDo();
            passWordLogDo.setUserId(getUserId());
            passWordLogDo.setDescription("用户" + getUser().getUsername() + "修改密码");
            passWordLogDo.setOperateTime(new Date());
            passWordLogDoService.insert(passWordLogDo);
        }catch (Exception ex){
            logger.error("用户修改密码"+getUser().getUsername()+"出错"+ex.toString());
        }
        return R.ok();
    }

    /**
     * 用户信息
     */
    @ApiOperation("用户信息")
    @GetMapping("/{userId}")
   /* @RequiresPermissions("sys:user:info")*/
    public R info(@PathVariable("userId") String userId) {
        SysUser user = sysUserService.selectById(userId);

        //获取用户所属的角色列表
        List<String> roleIdList = sysUserRoleService.queryRoleIdList(userId);
        user.setRoleIdList(roleIdList);

        return R.ok().put("user", user);
    }


    /**
     * 修改用户
     */
    @ApiOperation("修改用户")
    @PutMapping()
    @RequiresPermissions("sys:user:update")
    public R update(@RequestBody SysUser user) {
        ValidatorUtils.validateEntity(user, UpdateGroup.class);
        if ("1".equals(user.getId()) && user.getStatus() == 0) {
            return R.error(500, "超级管理员不允许禁用");
        }
        if (getUserId().equals(user.getId()) && user.getStatus() == 0) {
            return R.error(500, "不能禁用自己");
        }
        int count = sysUserService.queryByUserName(user.getUsername(), user);
        if (count > 0) {
            return R.error(500, "登录名称已存在");
        }
        if (StringUtils.isNotBlank(user.getPassword())) {
            //String alertInfo = "密码必须由";
            StringBuffer alertInfo = new StringBuffer("密码必须由");
            boolean pass = true;
            pass = AccountValidatorUtil.validatorPass(user.getPassword(), alertInfo);
            if (!pass) {
                return R.error(alertInfo.substring(0, alertInfo.length() - 1) + "组成");
            }
            user.setPassword(Base64Utils.base64Encrypt(user.getPassword()));
        }
        sysUserService.update(user);


        return R.ok();
    }

    /**
     * 删除用户
     */
    @ApiOperation("删除用户")
    @DeleteMapping("/{userId}")
    @RequiresPermissions("sys:user:delete")
    public R delete(@PathVariable("userId") String userId) {
        if ("1".equals(userId)) {
            return R.error("系统管理员不能删除");
        }
        if (getUserId().equals(userId)) {
            return R.error("不能删除自己");
        }


        sysUserService.deleteById(userId);
        sysRoleService.deleteById(userId);

        return R.ok();
    }

    @Autowired
    private SysRoleService roleService;

    @RequiresAuthentication
    @RequiresPermissions("sys:user:import")
    @ApiOperation(value = "批量导入用户", notes = "模板下载地址=/批量导入用户模板.xlsx")
    @PostMapping(value = "/importUser", consumes = "multipart/*", headers = "content-type=multipart/form-data")
    public R importUser(@ApiParam(value = "上传文件", required = true) MultipartFile file) {
        List<DeptDO> deptDOList = deptDOService.selectList(null);
        List<String> loginNames = sysUserService.selectList(null).stream().map(f -> f.getUsername()).collect(Collectors.toList());
        List<SysRole> roleList = roleService.selectList(null);
        List<ImportError> errors = new ArrayList<>();
        List<SysUser> list = new ArrayList<>();
        Workbook wb = null;
        try {
            String fileName = file.getOriginalFilename();
            if (!ExcelUtil.isExcel2007(fileName) && !ExcelUtil.isExcel2003(fileName)) {
                return R.error("导入的文件格式不正确");
            }
        } catch (Exception e) {
            return R.error("导入的文件格式不正确");
        }

        try {
            if (ExcelUtil.isExcel2007(file.getOriginalFilename())) {
                wb = new XSSFWorkbook(file.getInputStream());
            } else {
                wb = new HSSFWorkbook(file.getInputStream());
            }
        } catch (IOException e) {
            e.printStackTrace();
            return R.error("导入的文件出现错误");
        }
        //设置导入格式
        DataFormatter formatter = new DataFormatter(Locale.US);
        //获取第一张表
        Sheet sheet = wb.getSheetAt(0);
        int count = 0;
        if (sheet.getLastRowNum() <= 0) {
            return R.error("数据不能为空");
        }
        for (int i = 1; i <= sheet.getLastRowNum(); i++) {

            //获取索引为i的行，以0开始
            Row row = sheet.getRow(i);
            //获取第i行的索引为0的单元格数据
            String logiName = formatter.formatCellValue(row.getCell(0));
            System.out.println("登录名称" + logiName);

            if (StringUtils.isBlank(logiName)) {
                continue;
            } else {
                count++;
            }
            if (loginNames.contains(logiName)) {
                ImportError error = new ImportError();
                error.setColumnNum(i);
                error.setName(logiName);
                error.setErroMessage("登录名称已经存在");
                errors.add(error);
                continue;
            }
            if (logiName.length() > 20) {
                ImportError error = new ImportError();
                error.setColumnNum(i);
                error.setName(logiName);
                error.setErroMessage("登录名称不能超过20位");
                errors.add(error);
                continue;
            }
            //获取第i行的索引为1的单元格数据
            String passWord = formatter.formatCellValue(row.getCell(1));
            if (passWord.length() < 6) {
                ImportError error = new ImportError();
                error.setColumnNum(i);
                error.setName(logiName);
                error.setErroMessage("密码长度不足6位");
                errors.add(error);
                continue;
            }

            StringBuffer alertInfo = new StringBuffer("密码必须由");
            boolean pass = true;
            pass = AccountValidatorUtil.validatorPass(passWord, alertInfo);
            if (!pass) {
                ImportError error = new ImportError();
                error.setColumnNum(i);
                error.setName(logiName);
                error.setErroMessage(alertInfo.substring(0, alertInfo.length() - 1) + "组成");
                errors.add(error);
                continue;
            }
            //获取第i行的索引为2的单元格数据
            String comFrimPassword = formatter.formatCellValue(row.getCell(2));

            String name = formatter.formatCellValue(row.getCell(3));
            //称谓

            String sex = formatter.formatCellValue(row.getCell(4));

            String roles = formatter.formatCellValue(row.getCell(5));
            String dept = formatter.formatCellValue(row.getCell(6));
            String status = formatter.formatCellValue(row.getCell(7));
            Date brithDay = null;
            try {
                brithDay = row.getCell(8).getDateCellValue();
            } catch (Exception ex) {

            }

            String email = formatter.formatCellValue(row.getCell(9));
            String mobilePhone = formatter.formatCellValue(row.getCell(10));


            if (!passWord.equals(comFrimPassword)) {
                ImportError error = new ImportError();
                error.setColumnNum(i);
                error.setName(logiName);
                error.setErroMessage("两次密码不一致");
                errors.add(error);
                continue;
            }
            if (name.length() > 20) {
                ImportError error = new ImportError();
                error.setColumnNum(i);
                error.setName(logiName);
                error.setErroMessage("姓名长度不能超过20位");
                errors.add(error);
                continue;
            }
            if (StringUtils.isNotBlank(email) && !AccountValidatorUtil.isEmail(email)) {
                ImportError error = new ImportError();
                error.setColumnNum(i);
                error.setName(logiName);
                error.setErroMessage("邮箱格式不正确");
                errors.add(error);
                continue;
            }
            if (StringUtils.isNotBlank(mobilePhone) && !AccountValidatorUtil.isMobile(mobilePhone)) {
                ImportError error = new ImportError();
                error.setColumnNum(i);
                error.setName(logiName);
                error.setErroMessage("手机号码格式不正确");
                errors.add(error);
                continue;
            }
            SysUser user = new SysUser();
            user.setUsername(logiName.trim());
            user.setPassword(Base64Utils.base64Encrypt(passWord.trim()));
            String orgID = "";
            if (dept != null && !"".equals(dept)) {
                Optional<DeptDO> opOrg = deptDOList.stream()
                        .filter((e) -> {
                            return e.getName().equals(dept.trim());
                        }).findFirst();
                if (opOrg.isPresent()) {
                    DeptDO model = opOrg.get();
                    orgID = model.getId();
                }
            }
            if (StringUtils.isNotBlank(orgID)) {
                user.setDeptId(orgID);
            }
            if (StringUtils.isNotBlank(roles)) {
                String[] rolenames = roles.split(",");
                List<String> rolelist = new ArrayList<>();
                if (rolenames != null && rolenames.length > 0) {
                    for (String rname : rolenames) {
                        if (!StringUtils.isEmpty(rname)) {
                            String roleId = "";
                            Optional<SysRole> opRole = roleList.stream()
                                    .filter((e) -> {
                                        return e.getRoleName().equals(rname.trim());
                                    }).findFirst();
                            if (opRole.isPresent()) {
                                SysRole model = opRole.get();
                                roleId = model.getId();
                            }
                            if (StringUtils.isNotBlank(roleId)) {
                                rolelist.add(roleId);
                            }
                        }
                    }
                }

                if (rolelist.size() > 0) {
                    user.setRoleIdList(rolelist);
                }
            }
            user.setEmail(email);
            user.setMobile(mobilePhone);
            if (StringUtils.isNotBlank(status)) {
                user.setStatus(status.equals("禁用") ? 0 : 1);
            }
            user.setSex("男".equals(sex) ? 0 : 1);
            user.setName(name);

            if (brithDay != null) {
                user.setBirth(brithDay);
            }
            list.add(user);
            //获取第i行的索引为3的单元格数据

        }

        try {
            wb.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        int rightcount = 0;
        for (SysUser user : list) {
            try {
                Wrapper<SysUser> wrapper = new EntityWrapper<>();
                wrapper.eq("user_name", user.getUsername());
                if (sysUserService.selectCount(wrapper) <= 0) {
                    try {
                        boolean result = sysUserService.insert(user);
                        if (result) {
                            //添加虚拟角色
                            SysRole sysRole = new SysRole();
                            sysRole.setId(user.getId());
                            sysRole.setCreateTime(new Date());
                            sysRole.setInvented(1);
                            sysRole.setRoleName(user.getName() + "虚拟角色授权使用");
                            sysRole.setCreateAt(getUserId());
                            sysRole.setUpdateTime(new Date());
                            sysRoleService.insert(sysRole);
                            rightcount++;
                        }
                    } catch (Exception ex) {
                        ImportError error = new ImportError();
                        error.setName(user.getUsername());
                        error.setErroMessage("新增异常，请检查portal，openAm是否重复");
                        errors.add(error);
                        ex.printStackTrace();
                    }
                } else {
                    ImportError error = new ImportError();
                    error.setName(user.getUsername());
                    error.setErroMessage("已经存在登录名称");
                    errors.add(error);
                }

            } catch (Exception ex) {
                ImportError error = new ImportError();
                error.setName(user.getUsername());
                error.setErroMessage(ex.getMessage());
                errors.add(error);
            }
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("error", errors.size());
        jsonObject.put("errorInfo", errors);
        jsonObject.put("count", count);
        jsonObject.put("rightCount", rightcount);
        return R.ok(jsonObject);

    }


    @ApiOperation(value = "批量导出用户")
    @ApiImplicitParam(name = "ids", value = "用户ids逗号隔开", dataType = "String", paramType = "query")
    @GetMapping("exportExcel")
    @RequiresAuthentication
    @RequiresPermissions("sys:user:down")
    public void exportExcel(HttpServletResponse response, @PathParam("ids") String ids) throws Exception {


        ExcelData data = new ExcelData();
        Wrapper<SysUser> wrapper = new EntityWrapper<>();
        List<DeptDO> orglist = deptDOService.selectList(null);
        List<SysRole> roleList = sysRoleService.selectList(null);
        if (StringUtils.isNotBlank(ids)) {
            wrapper.in("id", ids);
        }
        List<SysUser> userlist = sysUserService.selectList(wrapper);
        if (userlist != null) {
            if (StringUtils.isNotBlank(ids)) {
                String[] idlist = ids.split(",");
                List<String> list = Arrays.asList(idlist);
                userlist = userlist.stream().filter(f -> {
                    return list.contains(f.getId());
                }).collect(Collectors.toList());
            }
        }
        if (userlist != null && userlist.size() > 0) {
            data.setName("批量导出用户");
            List<String> titles = new ArrayList();

            titles.add("登录名称");
            titles.add("用户名称");
            titles.add("性别");
            titles.add("用户角色");
            titles.add("所属部门");
            titles.add("状态");
            titles.add("出生日期");
            titles.add("邮箱");
            titles.add("电话");
            data.setTitles(titles);

            List<List<Object>> rows = new ArrayList();

            for (SysUser user1 : userlist) {
                List<Object> row = new ArrayList();
                row.add(user1.getUsername());
                row.add(user1.getName());
                if (user1.getSex() != null) {
                    row.add(user1.getSex() == 0 ? "男" : "女");
                } else {
                    row.add("");
                }
                //获取用户所属的角色列表
                List<String> roleIdList = sysUserRoleService.queryRoleIdList(user1.getId());
                if (roleIdList != null && roleIdList.size() > 0) {
                    String name = "";
                    StringBuilder rolesName = new StringBuilder();
                    for (String roleName : roleIdList) {
                        Optional<SysRole> sysRole = roleList.stream().filter(f -> f.getId().equals(roleName)).findFirst();
                        if (sysRole.isPresent()) {
                            rolesName.append(sysRole.get().getRoleName()).append(",");
                        }
                    }
                    if(rolesName!=null&&rolesName.length()>1) {
                        name = rolesName.substring(0, rolesName.length() - 1);
                    }else {
                        name=rolesName.toString();
                    }
                    row.add(name);
                } else {
                    row.add("");
                }

                if (StringUtils.isNotBlank(user1.getDeptId())) {
                    Optional<DeptDO> deptDOOptional = orglist.stream().filter(f -> f.getId().equals(user1.getDeptId())).findFirst();
                    if (deptDOOptional.isPresent()) {
                        row.add(deptDOOptional.get().getName());
                    } else {
                        row.add("");
                    }
                } else {
                    row.add("");
                }
                row.add(user1.getStatus() == 1 ? "启用" : "禁用");
                if (user1.getBirth() != null) {
                    row.add(DateUtils.format(user1.getBirth()));
                } else {
                    row.add("");
                }
                row.add(user1.getEmail());
                row.add(user1.getMobile());
                rows.add(row);
            }


            data.setRows(rows);
            //用DateFormat的format()方法在dt中获取并以yyyy/MM/dd HH:mm:ss格式显示
            //设置显示格式
            DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            String nowTime = "";
            nowTime = df.format(new Date());
            try {
                ExportExcelUtils.exportExcel(response, "批量导出用户" + nowTime + ".xlsx", data);
            }catch (Exception ex){
                ex.printStackTrace();
            }
        } else {

        }
    }

    @Autowired
    private  ShiroService shiroService;

    @ApiOperation(value = "获取用户权限list")
    @GetMapping("/getUserPermit/{userId}")
    @RequiresAuthentication
    public Result<Set<String>> getUserPermit(@PathVariable("userId")String userId){

        Set<String> permitSet= shiroService.getUserPermissions(userId);
        return  Result.ok(permitSet);
    }



}